<?php

namespace app\middleware;

use app\model\StationAccount;
use Closure;
use think\facade\Cache;

class StationMiddleware
{
    public function handle(\think\Request $request, Closure $next)
    {
        $authorization = $request->header('authorization');
        if (empty($authorization)) {
            return response(json_encode(['errMsg' => '异常登录', 'errCode' => 7004], 320), 401);
        }
        $authorization = json_decode($authorization, true);
//        dd($authorization);
        $token = Cache::get('station_'.$authorization['token']);
        if (empty($token) || $token['expire_time'] < time()) {
            Cache::delete($authorization['token']);
            return response(json_encode(['errMsg' => '登录已过期', 'errCode' => 7004], 320), 401);
        }
        $last_time = strtotime("+1 hour");
        if ($token['expire_time'] < $last_time) {
            //一小时以内访问自动延期24小时
            $token['expire_time'] = strtotime("+24 Hours");
        }
        Cache::set($authorization['token'], $token, $token['expire_time']);
//        $account = Account::where('id', $token['id'])->where('state', 1)->where('is_del', 1)->find();
        $account = app(StationAccount::class)->with(['station'])->where('id', $token['id'])->where('state', 1)->find();
        if (empty($account)) return response(json_encode(['errMsg' => '非法登录账号', 'errCode' => 7004], 320), 401);
//        if ($account['id'] != $token['id']) {
//            return response(json_encode(['errMsg' => '非法登录账号', 'errCode' => 7004], 320), 401);
//        }
        $request->account = $account;
        return $next($request);
    }
}
